package cn.itcast.myapplication.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.itcast.myapplication.R;
import cn.itcast.myapplication.viewemodel.MyViewModel;
import cn.itcast.myapplication.viewemodel.ViewModelWithLiveData;

public class MyLiveData extends AppCompatActivity {


    ViewModelWithLiveData viewModelWithLiveData;

    @BindView(R.id.add)
    ImageButton add;

    @BindView(R.id.add2)
    ImageButton add2;

    @BindView(R.id.tv_number)
    TextView tv_number;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_live_data);

        ButterKnife.bind(this);//这段代码一定要加上不然会导致程序启动失败内存溢出，程序崩溃

        viewModelWithLiveData=new ViewModelProvider(this).get(ViewModelWithLiveData.class);//ViewModel的绑定

        //设置数据观察者 当数据变化时会通知这个函数
        viewModelWithLiveData.getLikedNumbfer().observe(this, new Observer<Integer>() {

            @Override
            public void onChanged(Integer integer) {

                tv_number.setText(String.valueOf(integer));

            }
        });


        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                viewModelWithLiveData.addLikedNumber(1);

            }
        });


        add2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                viewModelWithLiveData.addLikedNumber(-1);

            }
        });

    }
}
